KcpChannelResolver = class("KcpChannelResolver");
KcpChannelResolver.PING_INTERVAL = 5

function KcpChannelResolver:ctor(kcp)
    self.kcpChannel = kcp
    self.pingIntervalTime = 0

    local addEvent = function(action,func)
        if action then
            return  action + func
        else
            return func
        end
    end
    self.kcpChannel.OnRevData = addEvent(self.kcpChannel.OnRevData,handler(self, self.OnRevData));
end

function KcpChannelResolver:Tick()
    self.pingIntervalTime = self.pingIntervalTime + Time.fixedDeltaTime
    if self.pingIntervalTime >= KcpChannelResolver.PING_INTERVAL then
        self.pingIntervalTime = 0
        self:Send(MsgType.PING, 0, '')
    end
end

function KcpChannelResolver:Connect(host, port, conv)
    self.kcpChannel:Connect(host, port, conv);
    FixedUpdateBeat:Add(self.Tick, self)
end

function KcpChannelResolver:KcpClose()
    FixedUpdateBeat:Remove(self.Tick, self)
    self.kcpChannel:Close();
end

function KcpChannelResolver:Send(msgID, requestID, bytes)
    local gameProtocol = GameMessage.Protocol()
    gameProtocol.messageType = msgID
    gameProtocol.code = ResponseCode.SUCCESS
    gameProtocol.requestID = requestID
    gameProtocol.data = bytes
    self.kcpChannel:Send(gameProtocol:SerializeToString())
end

function KcpChannelResolver:OnRevData(bytes)
    local msg = GameMessage.Protocol()
    msg:ParseFromString(bytes)
    --print('##########################Recv##########################',msgID, requestID)
    local code = msg.code
    local requestID = msg.requestID
    local msgID = msg.messageType

    if code == ResponseCode.FAILED then
        if requestID == 0 then
            EVTM.dispatch(EVENT.SYS_TCP_RECEIVE_ERR, code)
            --logError('####################ErrorCode####################### ' .. tostring(code))
        else
            RpcUtils.OnReceiveException(requestID, code)
        end
    else
        if requestID == 0 then
            EVTM.dispatch(EVENT.SYS_TCP_RECEIVE_MSG..tostring(msgID), {msg.data})
        else
            RpcUtils.OnReceiveRpc(requestID, msg.data)
        end
    end
end